package org.flowers.unbeaten.security;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;
import org.flowers.unbeaten.config.proprety.CustomerRedisProperty;
import org.flowers.unbeaten.exception.BusinessException;
import org.flowers.unbeaten.exception.code.BaseResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * @description 自定义哈希凭证匹配器
 * @author RyanWang
 * @date 2021-07-16 15:35:28
 * @version 1.0
 */
public class MyHashedCredentialsMatcher extends SimpleCredentialsMatcher {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CustomerRedisProperty customerRedisProperty;

    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        String accessToken = (String) token.getPrincipal();
        // 判断当前用户的token是否存在Redis中
        if (!redisTemplate.hasKey(customerRedisProperty.getUserTokenPrefix() + accessToken)) {
            SecurityUtils.getSubject().logout();
            throw new BusinessException(BaseResponseCode.TOKEN_ERROR);
        }
        return true;
    }
}
